package kyuu.acshmily.net
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import kyuu.acshmily.events.LoaderEvent;

	[Event(name="loadComplete", type="kyuu.acshmily.events.LoaderEvent")]

	/**
	 * 弹幕加载器
	 */
	public class CommentLoader extends EventDispatcher
	{
		private static const loaderURL:String = "./load_comment.php";
		private var loader:URLLoader = null;

		public function CommentLoader(){}

		/**
		 * 加载指定视频的弹幕信息
		 */
		public function load(vid:String):void{
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, completeHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			try{
				var req:URLRequest = new URLRequest(loaderURL + "?vid=" + vid + "&baka=" + Math.random());
				loader.load(req);
			}
			catch(err:Error){
				trace(err.message);
			}
		}

		/**
		 * 释放连接
		 */
		public function close():void{
			if(loader == null) return;

			loader.removeEventListener(Event.COMPLETE, completeHandler);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			loader.close();
			loader = null;
		}
		
		/**
		 * 加载完成的事件处理函数
		 */
		private function completeHandler(e:Event):void{
			var le:LoaderEvent = new LoaderEvent(LoaderEvent.LOAD_COMPLETE, false, false, loader.data);
			dispatchEvent(le);
		}

		/**
		 * IO错误的事件处理函数
		 */
		private function errorHandler(e:IOErrorEvent):void{
			trace(e.text);
		}
	}
}